﻿#include "MainWindowSignalHandler.h"
#include "BaseWidget/IdaDialogMsg.h"
#include "CenterWidget.h"
#include "MainWindow.h"
#include "Graph3DWindowBase.h"
#include <QDomNodeList>
#include <QDomElement>
#include <QDomDocument>
#include <QDomAttr>
#include <iostream>
#include "AnimationSettingDialog.h"
#include "PolarCoordinateGraphWindow.h"
#include "LineChartWindow.h"
#include "DialogDataImportConfiguration.h"
#include "HeatMapWindow.h"
#include "ThreeDCloudMapWindow.h"
#include "ThreeDSurfacePlotWindow.h"
#include "SurfaceElectricFieldMapWindow.h"
#include "DialogCurveSmoothing.h"
#include "DialogInterpolation.h"
#include "DialogTotalQuantityCalculation.h"
#include "DialogEvaluationSubmission.h"
#include "DialogHirfExtrapolation.h"
#include "DialogShieldingEfficiency.h"
#include "DialogTransferFunction.h"
#include "DialogIPLCalculation.h"
#include "DialogWaveformAnalysis.h"
#include "PostEnumType.h"
#include "Curve2DPlotor.h"
#include "TableChatWindow.h"
#include "BaseModule/IBaseSignal.h"
#include "BaseModule/GlobalHelper.h"
#include "BaseWidget/IWidgetSignal.h"

namespace pst
{
    MainWindowSignalHandler* MainWindowSignalHandler::m_instance = nullptr;

    // 获取单例
    MainWindowSignalHandler* MainWindowSignalHandler::getInstance()
    {
        if (m_instance == nullptr)
        {
            m_instance = new MainWindowSignalHandler;
        }
        return m_instance;
    }

    CurrentWindowType MainWindowSignalHandler::getCurrentGraphWindowType()
    {
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        if (qobject_cast<LineChartWindow*>(currentGraph) != nullptr) // 二维折线图
        {
            return CurrentWindowType::TwoDGraph;
        }
        else if (qobject_cast<PolarCoordinateGraphWindow*>(currentGraph)) // 极坐标图
        {
            return CurrentWindowType::PolarGraph;
        }
        else if (qobject_cast<HeatMapWindow*>(currentGraph)) // 二维热力图
        {
            return CurrentWindowType::TwoDHeatMap;
        }
        else if (qobject_cast<ThreeDCloudMapWindow*>(currentGraph)) // 三维云图
        {
            return CurrentWindowType::ThreeDCloudMap;
        }
        else if (qobject_cast<ThreeDSurfacePlotWindow*>(currentGraph)) // 三维曲面图
        {
            return CurrentWindowType::ThreeDSurfacePlot;
        }
        else if (qobject_cast<SurfaceElectricFieldMapWindow*>(currentGraph)) // 表面电场图
        {
            return CurrentWindowType::SurfaceElectricFieldMap;
        }
        else if (qobject_cast<TableChatWindow*>(currentGraph)) // 数据表格
        {
            return CurrentWindowType::DataTable;
        }
        else
        {
            // 无图
            return CurrentWindowType::None;
        }
    }

    void MainWindowSignalHandler::readDataFromProjectFile(QDomNodeList* nodeList)
    {
        const int _nodeCount = nodeList->size();
        if (_nodeCount != 1)
        {
            return;
        }
        QDomElement root = nodeList->at(0).toElement();

        QDomNodeList elemModelList = root.elementsByTagName("GraphWindow");

        auto _centerWidget = MainWindowSignalHandlerInstance->getCenterWidget();
        auto elemModelListCount = elemModelList.size();
        for (int i = 0; i < elemModelListCount; ++i)
        {
            QDomElement elemModel = elemModelList.at(i).toElement();

            auto _windowType = elemModel.attribute("WindowType");
            auto _windowUniversalID = elemModel.attribute("WindowUniversalID").toInt();
            WindowTotalDataInstance->appendWindowUniversalID(_windowUniversalID);
            int _windowID = elemModel.attribute("WindowID").toInt();
            if (_windowType == "LineChartWindow")// 二维折线
            {
                auto _lineChartWindow = _centerWidget->addNewGraph2D(pst::GraphType::TwoDLineChart, _windowUniversalID, _windowID);
                _lineChartWindow->readFromProjectFile(&elemModel);
            }
            else if (_windowType == "PolarCoordinateGraphWindow")// 极坐标
            {
                auto _polarCoordinateGraphWindow = _centerWidget->addNewGraph2D(pst::GraphType::PolarGraph, _windowUniversalID, _windowID);
                _polarCoordinateGraphWindow->readFromProjectFile(&elemModel);
            }
            else if (_windowType == "HeatMapWindow")//热力图
            {
                auto _heatMapWindow = _centerWidget->addNewGraph2D(pst::GraphType::TwoDHeatMap, _windowUniversalID, _windowID);
                _heatMapWindow->readFromProjectFile(&elemModel);
            }
            else if (_windowType == "SurfaceElectricFieldMapWindow")//表面分布图
            {
                auto _surfaceElectricFieldMapWindow = _centerWidget->addNewGraph3D(pst::GraphType::SurfaceElectricFieldMap, _windowUniversalID, _windowID);
                _surfaceElectricFieldMapWindow->readFromProjectFile(&elemModel);
            }
            else if (_windowType == "ThreeDCloudMapWindow")// 三维云图
            {
                auto _threeDCloudMapWindow = _centerWidget->addNewGraph3D(pst::GraphType::ThreeDCloudMap, _windowUniversalID, _windowID);
                _threeDCloudMapWindow->readFromProjectFile(&elemModel);
            }
            else if (_windowType == "ThreeDSurfacePlotWindow")//三维曲面图
            {
                auto _threeDSurfacePlotWindow = _centerWidget->addNewGraph3D(pst::GraphType::ThreeDSurfacePlot, _windowUniversalID, _windowID);
                _threeDSurfacePlotWindow->readFromProjectFile(&elemModel);
            }
            else if (_windowType == "TableChatWindow")
            {
                TableChatWindow* _tableChatWindow = new TableChatWindow(_centerWidget);
                _tableChatWindow->readFromProjectFile(&elemModel);

                WindowTotalDataInstance->addGraph3DWindow(_tableChatWindow);
                _centerWidget->getTabWidget()->addTab(_tableChatWindow, QStringLiteral("表格") + QString::number(_tableChatWindow->getWindowID() + 1));
                _centerWidget->getTabWidget()->setCurrentWidget(_tableChatWindow);
            }
        }     
    }

    TextFileParser* MainWindowSignalHandler::getTextFileParserByProjectTreeItem(int projectTreeItemID)
    {
        return m_mainWindow->getTextFileParserByProjectTreeItem(projectTreeItemID);
    }

    TextFileParser* MainWindowSignalHandler::getTextFileParserByDataSourceByOpenProject(QString dataSources)
    {
        return m_mainWindow ->getTextFileParserByDataSourceByOpenProject(dataSources);
    }

    InfomationGraph3DBasical* MainWindowSignalHandler::BuildCompleteGraph3DInfoByProjectTreeItem(int projectTreeItemID, GraphType graphType)
    {
        if (graphType == GraphType::ThreeDCloudMap)
            return m_mainWindow->BuildCompleteGraph3DInfoByProjectTreeItemThreeDCloudMap( projectTreeItemID);
        else if (graphType == GraphType::ThreeDSurfacePlot)
            return m_mainWindow->BuildCompleteGraph3DInfoByProjectTreeItemThreeDSurfacePlot(projectTreeItemID);
        else if (graphType == GraphType::SurfaceElectricFieldMap)
            return m_mainWindow->BuildCompleteGraph3DInfoByProjectTreeItemSurfaceElectricFieldMap( projectTreeItemID);
        else if (graphType == GraphType::TableChart)
            return m_mainWindow->BuildCompleteGraph3DInfoByProjectTreeItemTableChart(projectTreeItemID);
        return nullptr;
    }

    // 主页

    void MainWindowSignalHandler::slot_toolButtonOpenProjectFile()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        //检测当前是否有数据
        auto _simulationDataTempDir = GlobalHelperInstance->getSimulationDataTempDir();
        auto _ImportDataTempDir = GlobalHelperInstance->getImportDataTempDir();

        EDialogMsgResult _res = EDialogMsgResult::Second; // 默认不保存
        QDir _dir1(_simulationDataTempDir);
        QDir _dir2(_ImportDataTempDir);
        _dir1.setFilter(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
        _dir2.setFilter(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
        if (!_dir1.entryList().isEmpty() || !_dir2.entryList().isEmpty())
        {
            _res = IdaDialogMsg::showDialog(m_mainWindow, QStringLiteral("当前操作是否保存为一个工程文件？"), EDialogMsg::Custom, QStringLiteral("打开工程文件"), {QStringLiteral("取消,不保存,保存").split(",")});
        }

        if (_res == EDialogMsgResult::Third)
        {
            slot_toolButtonProjectResultSave();
        }
        else if (_res == EDialogMsgResult::Second)
        {
            QString _dir = QString("C:/");
            auto _projectFilepath = QFileDialog::getOpenFileName(m_mainWindow, QString("打开工程文件"), _dir, tr("*.ppc"));
            if (_projectFilepath.isEmpty())
                return;
            GlobalHelperInstance->setIsNeedPopupWindow(false);
            emit IBaseSignalInstance->signal_openProjectFile(_projectFilepath);
            GlobalHelperInstance->setIsNeedPopupWindow(true);
        }
        else
            return;
    }
    void MainWindowSignalHandler::slot_toolButtonProjectResultSave()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        QString _dir = QString("C:/");
        QString _suffix = "PostProcessing(*.ppc)";
        QString _title = QStringLiteral("保存工程结果");
        QString _filenames = QFileDialog::getSaveFileName(m_mainWindow, _title, _dir, _suffix);
        if (_filenames.isEmpty())
            return;
        emit IBaseSignalInstance->signal_saveProjectResult(_filenames);
    }
    void MainWindowSignalHandler::slot_toolButtonDataImport(QString lastSelectPath)
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto filepath = QFileDialog::getOpenFileName(m_mainWindow, QString("导入数据"), lastSelectPath, tr("*.txt\n *.csv\n *.vtu\n *.vtk\n *.vtp"));
        if (filepath.isEmpty())
            return;
        QFileInfo _fileInfo;
        _fileInfo.setFile(filepath);
        if (_fileInfo.suffix() != "txt" && _fileInfo.suffix() != "csv")
        {
            QStringList _pyCodes;
            _pyCodes.append(QString("PostProcessing.dataImport('%1',%2,'%3')").arg(filepath).arg(false).arg(QString()));//文件路径，是否是txt和csv，txt和csv的数据
            emit IBaseSignalInstance->signal_execPYCode(_pyCodes, true, false);
        }
        emit IBaseSignalInstance->singal_toolButtonDataImport(filepath);
    }
    void MainWindowSignalHandler::slot_toolButtonFormatViewClicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        auto lineChartWindow = qobject_cast<LineChartWindow*>(currentGraph);
        // 借助slot_checkGraphType判断的按钮是否可用来判断选中数据类型
        //  添加到当前图：只允许二维折线、极坐标、三维云图、三维曲面图
        if (lineChartWindow != nullptr && !m_mainWindow->m_standardExampleData.isEmpty())
        {

            auto textFileParser = m_mainWindow->m_standardExampleData.at(m_mainWindow->m_comboBoxStandardSelection->currentIndex());
            textFileParser->setScanParameterIndex(0);
            QVector<QVector<double>> tmp;
            for (int i = 1; i < textFileParser->getEachColNameOfKey().size(); ++i)
            {
                tmp.append(QVector<double>(1, 0));
            }
            textFileParser->setOtherKeyParameter(tmp);
            QList<Info2DPointer> yList;
            QPair<int, int> tem{m_mainWindow->m_comboBoxDataSelection->currentIndex(), 0};

            textFileParser->getChosenLinesFromKey(QList<QPair<int, int>>{tem}, yList);
            if (('[' + textFileParser->getEachColUnitOfKey().at(textFileParser->getScanParameterIndex()) + ']') != lineChartWindow->GetUnit())
            {
                auto _res = IdaDialogMsg::showDialog(nullptr, QStringLiteral("变量类型或单位不一致！"), EDialogMsg::Error, QStringLiteral("添加错误"));
                return;
            }

            for (auto& info : yList)
            {
                info->setIsNewData(true);
                info->setIsOnlyShow(true);
                info->setGraph(lineChartWindow);
                info->setStandardCurveParserFileName(textFileParser->GetFileName().split('/').last());
                info->setDataSources(m_mainWindow->m_comboBoxStandardSelection->currentText());
                lineChartWindow->slot_addStandardCcurve(info);
            }
        }
    }
    void MainWindowSignalHandler::slot_comboBoxStandardSelectionCurrentIndexChanged(int index)
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        for (const auto& pair : m_mainWindow->m_fileValueData)
        {
            if (pair.first == m_mainWindow->m_comboBoxStandardSelection->itemText(index))
            {
                m_mainWindow->m_comboBoxDataSelection->clear();
                m_mainWindow->m_comboBoxDataSelection->addItems(pair.second);
                break;
            }
        }
    }
    void MainWindowSignalHandler::slot_comboBoxDataSelectionCurrentIndexChanged(int index)
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        // printErrorMessage();
    }

    void MainWindowSignalHandler::slot_toolButtonAIQAClicked()
    {
        printErrorMessage();
    }

    // 数据分析
    void MainWindowSignalHandler::slot_toolButtonTotalQuantityCalculation()
    {
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        auto lineChartWindow = qobject_cast<LineChartWindow*>(currentGraph);
        // 借助slot_checkGraphType判断的按钮是否可用来判断选中数据类型
        if (lineChartWindow == nullptr)
        {
            return;
        }
        QStringList graphNames;
        auto customPlot = lineChartWindow->getPlotor();
        for (int i = 0; i < customPlot->graphCount(); ++i)
        {
            graphNames.append(customPlot->graph(i)->name());
        }
        auto _dialog = new DialogTotalQuantityCalculation();
        _dialog->setCurveNameList(graphNames);
        connect(_dialog, &DialogTotalQuantityCalculation::signal_totalCalculation, lineChartWindow, &LineChartWindow::slot_totalCalculation);
        _dialog->showWindow();
    }

    void MainWindowSignalHandler::slot_toolButtonThunderstormZoneClicked()
    {
        m_mainWindow->slot_toolButtonThunderstormZoneClicked();
    }

    void MainWindowSignalHandler::slot_toolButtonHirfExtrapolationClicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        auto lineChartWindow = qobject_cast<LineChartWindow*>(currentGraph);
        // 借助slot_checkGraphType判断的按钮是否可用来判断选中数据类型
        if (lineChartWindow == nullptr)
        {
            return;
        }
        lineChartWindow->setIsEdit(isEdit());
        QString _pyCode = QString("PostProcessing.lineChartWindowSetIsEdit(%1)").arg(isEdit());
        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
        QStringList graphNames;
        auto customPlot = lineChartWindow->getPlotor();
        for (int i = 0; i < customPlot->graphCount(); ++i)
        {
            graphNames.append(customPlot->graph(i)->name());
        }
        QStringList HIRFNames;
        for (auto textFileParser : m_mainWindow->m_HIRFExtrapolation)
        {
            HIRFNames.append(QFileInfo(textFileParser->GetFileName()).completeBaseName());
        }
        auto _dialog = new DialogHirfExtrapolation();
        _dialog->setCurveNameList(graphNames);
        _dialog->setExtrapolationCoefficientList(HIRFNames);
        if (isEdit()) // 编辑初始化
            _dialog->setInit(getInitParams(lineChartWindow));
        //connect(_dialog, &DialogHirfExtrapolation::signal_computeHIRF, this, &MainWindowSignalHandler::slot_computeHIRF);
        connect(_dialog, &DialogHirfExtrapolation::signal_computeHIRF, this, [this](const QString& graphNames, double incidentWaveFieldValue, const QString& HIRFName, const QString& typeName, bool isCheckBoxChecked)
                { 
                return slot_computeHIRF(graphNames,incidentWaveFieldValue,HIRFName,typeName, isCheckBoxChecked); });

        _dialog->showWindow();
    }
    void MainWindowSignalHandler::slot_toolButtonIPLCalculationClicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        auto lineChartWindow = qobject_cast<LineChartWindow*>(currentGraph);
        // 借助slot_checkGraphType判断的按钮是否可用来判断选中数据类型
        if (lineChartWindow == nullptr)
        {
            return;
        }
        lineChartWindow->setIsEdit(isEdit());

        QString _pyCode = QString("PostProcessing.lineChartWindowSetIsEdit(%1)").arg(isEdit());
        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
        QStringList graphNames;
        auto customPlot = lineChartWindow->getPlotor();
        for (int i = 0; i < customPlot->graphCount(); ++i)
        {
            graphNames.append(customPlot->graph(i)->name());
        }
        auto _dialog = new DialogIPLCalculation();
        _dialog->setCurveNameList(graphNames);
        if (isEdit()) // 编辑初始化
            _dialog->setInit(getInitParams(lineChartWindow));
        connect(_dialog, &DialogIPLCalculation::signal_sendIPLDatas, [this, lineChartWindow](const QList<QVariant>& IPLDatas, bool* success)
                { lineChartWindow->slot_computeIPL(IPLDatas, success); });
        _dialog->showWindow();
    }
    void MainWindowSignalHandler::slot_toolButtonWaveformAnalysisClicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        auto lineChartWindow = qobject_cast<LineChartWindow*>(currentGraph);
        // 借助slot_checkGraphType判断的按钮是否可用来判断选中数据类型
        if (lineChartWindow == nullptr)
        {
            return;
        }
        lineChartWindow->setIsEdit(isEdit());
        QString _pyCode = QString("PostProcessing.lineChartWindowSetIsEdit(%1)").arg(isEdit());
        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
        QStringList graphNames;
        auto customPlot = lineChartWindow->getPlotor();
        for (int i = 0; i < customPlot->graphCount(); ++i)
        {
            graphNames.append(customPlot->graph(i)->name());
        }
        auto _dialog = new DialogWaveformAnalysis();
        _dialog->setCurveNameList(graphNames);
        if (isEdit()) // 编辑初始化
            _dialog->setInit(getInitParams(lineChartWindow));
        connect(_dialog, &DialogWaveformAnalysis::signal_sendAnalysisData, lineChartWindow, &LineChartWindow::slot_computeWaveformAnalysis);
        _dialog->showWindow();
    }
    void MainWindowSignalHandler::slot_toolButtonLightningZoningClicked()
    {
        printErrorMessage();
    }

    void MainWindowSignalHandler::slot_toolButtonShieldingEfficiencyClickedFormCommad(const QString& graphNames, double e0)
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        auto lineChartWindow = qobject_cast<LineChartWindow*>(currentGraph);
        // 借助slot_checkGraphType判断的按钮是否可用来判断选中数据类型
        if (lineChartWindow == nullptr)
        {
            return;
        }
        lineChartWindow->setIsEdit(isEdit());
        QString _pyCode = QString("PostProcessing.lineChartWindowSetIsEdit(%1)").arg(isEdit());
        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
        //QStringList graphNames;
        //auto customPlot = lineChartWindow->getPlotor();
        //for (int i = 0; i < customPlot->graphCount(); ++i)
        //{
        //    graphNames.append(customPlot->graph(i)->name());
        //}
        auto graphNameList = graphNames.split("\n");
        lineChartWindow->slot_computeEffectiveness(graphNameList, e0); 
    }
    void MainWindowSignalHandler::slot_toolButtonShieldingEfficiencyClicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        auto lineChartWindow = qobject_cast<LineChartWindow*>(currentGraph);
        // 借助slot_checkGraphType判断的按钮是否可用来判断选中数据类型
        if (lineChartWindow == nullptr)
        {
            return;
        }
        lineChartWindow->setIsEdit(isEdit());
        QString _pyCode = QString("PostProcessing.lineChartWindowSetIsEdit(%1)").arg(isEdit());
        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
        QStringList graphNames;
        auto customPlot = lineChartWindow->getPlotor();
        for (int i = 0; i < customPlot->graphCount(); ++i)
        {
            graphNames.append(customPlot->graph(i)->name());
        }
        auto _dialog = new DialogShieldingEfficiency();
        _dialog->setCurveNameList(graphNames);
        if (isEdit()) // 编辑初始化
            _dialog->setInit(getInitParams(lineChartWindow));
        connect(_dialog, &DialogShieldingEfficiency::signal_computeEffectiveness, [this, lineChartWindow](const QString& graphNames, double e0)
                {
                auto graphNameList = graphNames.split("\n");
                lineChartWindow->slot_computeEffectiveness(graphNameList, e0); 
                QString _pyCode = QString("PostProcessing.lineChartComputeEffectiveness('%1', %2)").arg(graphNames).arg(e0).remove(QRegExp("[\r\n]"));
                emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false); 
            });


        _dialog->showWindow();

        // auto _dialog = new DialogShieldingEfficiency();
        //_dialog->showWindow();
    }

    void MainWindowSignalHandler::slot_toolButtonTransferFunctionClicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        auto lineChartWindow = qobject_cast<LineChartWindow*>(currentGraph);
        // 借助slot_checkGraphType判断的按钮是否可用来判断选中数据类型
        if (lineChartWindow == nullptr)
        {
            return;
        }
        lineChartWindow->setIsEdit(isEdit());
        QString _pyCode = QString("PostProcessing.lineChartWindowSetIsEdit(%1)").arg(isEdit());
        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
        QStringList graphNames;
        auto customPlot = lineChartWindow->getPlotor();
        for (int i = 0; i < customPlot->graphCount(); ++i)
        {
            graphNames.append(customPlot->graph(i)->name());
        }
        auto _dialog = new DialogTransferFunction();
        _dialog->setCurveNameList(graphNames);
        if (isEdit()) // 编辑初始化
            _dialog->setInit(getInitParams(lineChartWindow));
        connect(_dialog, &DialogTransferFunction::signal_sendSelectInfo, [this, lineChartWindow](const QString& graphName, const QString& calibrationGraphName, const QString& type)
                { lineChartWindow->slot_computeTransferFunction(graphName, calibrationGraphName, type); });
        _dialog->showWindow();
    }

    void MainWindowSignalHandler::slot_toolButtonFFTClicked()
    {
        printErrorMessage();
    }
    void MainWindowSignalHandler::slot_toolButtonBasicAnalysisClicked()
    {
        printErrorMessage();
    }
    void MainWindowSignalHandler::slot_toolButtonCorrelationAnalysisClicked()
    {
        printErrorMessage();
    }
    void MainWindowSignalHandler::slot_toolButtonCumulativeDistributionFunctionClicked()
    {
        printErrorMessage();
    }
    void MainWindowSignalHandler::slot_toolButtonCurveSmoothingClicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        auto lineChartWindow = qobject_cast<LineChartWindow*>(currentGraph);
        lineChartWindow->setIsEdit(isEdit());
        QString _pyCode = QString("PostProcessing.lineChartWindowSetIsEdit(%1)").arg(isEdit());
        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
        auto _dialogCurveSmoothing = new DialogCurveSmoothing(m_mainWindow, lineChartWindow);
        if (isEdit()) // 编辑初始化
            _dialogCurveSmoothing->setInit(getInitParams(lineChartWindow));
        _dialogCurveSmoothing->showWindow();
    }
    void MainWindowSignalHandler::slot_toolButtonLinearInterpolationClicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        auto lineChartWindow = qobject_cast<LineChartWindow*>(currentGraph);
        lineChartWindow->setIsEdit(isEdit());
        QString _pyCode = QString("PostProcessing.lineChartWindowSetIsEdit(%1)").arg(isEdit());
        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
        auto _dialogInterpolation = new DialogInterpolation(m_mainWindow, lineChartWindow);
        if (isEdit()) // 编辑初始化
            _dialogInterpolation->setInit(getInitParams(lineChartWindow));
        _dialogInterpolation->setInterpolationType(InterpolationType::linearInterpolation);
        _dialogInterpolation->showWindow();
    }
    void MainWindowSignalHandler::slot_toolButtonLogarithmicInterpolationSingleAxisXClicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        auto lineChartWindow = qobject_cast<LineChartWindow*>(currentGraph);
        lineChartWindow->setIsEdit(isEdit());
        QString _pyCode = QString("PostProcessing.lineChartWindowSetIsEdit(%1)").arg(isEdit());
        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
        auto _dialogInterpolation = new DialogInterpolation(m_mainWindow, lineChartWindow);
        if (isEdit()) // 编辑初始化
            _dialogInterpolation->setInit(getInitParams(lineChartWindow));
        _dialogInterpolation->setInterpolationType(InterpolationType::logarithmicInterpolationSingleAxisX);
        _dialogInterpolation->showWindow();
    }
    void MainWindowSignalHandler::slot_toolButtonLogarithmicInterpolationSingleAxisYClicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        auto lineChartWindow = qobject_cast<LineChartWindow*>(currentGraph);
        lineChartWindow->setIsEdit(isEdit());
        QString _pyCode = QString("PostProcessing.lineChartWindowSetIsEdit(%1)").arg(isEdit());
        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
        auto _dialogInterpolation = new DialogInterpolation(m_mainWindow, lineChartWindow);
        if (isEdit()) // 编辑初始化
            _dialogInterpolation->setInit(getInitParams(lineChartWindow));
        _dialogInterpolation->setInterpolationType(InterpolationType::logarithmicInterpolationSingleAxisY);
        _dialogInterpolation->showWindow();
    }
    void MainWindowSignalHandler::slot_toolButtonLogarithmicInterpolationDoubleAxisClicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        auto lineChartWindow = qobject_cast<LineChartWindow*>(currentGraph);
        lineChartWindow->setIsEdit(isEdit());
        QString _pyCode = QString("PostProcessing.lineChartWindowSetIsEdit(%1)").arg(isEdit());
        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
        auto _dialogInterpolation = new DialogInterpolation(m_mainWindow, lineChartWindow);
        if (isEdit()) // 编辑初始化
            _dialogInterpolation->setInit(getInitParams(lineChartWindow));
        _dialogInterpolation->setInterpolationType(InterpolationType::logarithmicInterpolationDoubleAxis);
        _dialogInterpolation->showWindow();
    }
    void MainWindowSignalHandler::slot_toolButtonSplineInterpolationClicked()
    {
    }
    void MainWindowSignalHandler::slot_toolButtonPolynomialInterpolationClicked()
    {
    }

    // void MainWindowSignalHandler::slot_measureButtonClicked()
    // {
    //     if (m_centerWidget == nullptr)
    //     {
    //         return;
    //     }
    //     auto currentGraph = m_centerWidget->getCurrentGraphWindow();
    //     // 借助slot_checkGraphType判断的按钮是否可用来判断选中数据类型
    //     LineChartWindow* graph2DWindow = qobject_cast<LineChartWindow*>(currentGraph);
    //     if (graph2DWindow != nullptr)
    //     {
    //         auto action = qobject_cast<QAction*>(sender());
    //         if (action != nullptr)
    //         {
    //             graph2DWindow->slot_measureData(action->text());
    //         }
    //     }
    // }

    void MainWindowSignalHandler::slot_measureButtonClicked(MeasureType type, double value)
    {
        if (m_centerWidget == nullptr)
        {
            return;
        }
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        // 借助slot_checkGraphType判断的按钮是否可用来判断选中数据类型
        LineChartWindow* graph2DWindow = qobject_cast<LineChartWindow*>(currentGraph);
        if (graph2DWindow != nullptr)
        {
            graph2DWindow->slot_measureData(type, value);
            return;
        }

        PolarCoordinateGraphWindow* polarWindow = qobject_cast<PolarCoordinateGraphWindow*>(currentGraph);
        if (polarWindow)
        {
            polarWindow->measureData(type);
            return;
        }
    }

    void MainWindowSignalHandler::slot_toolButtonEvaluationSubmission()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        QMultiHash<int, QString> _nameHash;
        auto _itemHash = m_mainWindow->getEvaluationSubmissionNodeCorrespondenceData();
        for (auto it = _itemHash.begin(); it != _itemHash.end(); ++it)
        {
            _nameHash.insert(it.key(), it.value()->text());
        }

        auto _dialog = new DialogEvaluationSubmission();
        _dialog->setCurveNameHash(_nameHash);
        //connect(_dialog, &DialogEvaluationSubmission::signal_submitEvaluation, lineChartWindow, &LineChartWindow::slot_submitEvaluation);
        connect(_dialog, &DialogEvaluationSubmission::signal_submitEvaluation, this, &MainWindowSignalHandler::slot_submitEvaluationGlobal);
        _dialog->showWindow();
    }

    void MainWindowSignalHandler::slot_submitEvaluationGlobal(int emulationType, const QStringList& graphNameList)
    {
        if (emulationType == -1)
            return;
        auto _itemHash = m_mainWindow->getEvaluationSubmissionNodeCorrespondenceData();
        auto _itemList = _itemHash.values(emulationType);
        QList<QString> _filePaths{};
        for (auto _name : graphNameList)
        {
            if (!_name.isEmpty())
            {
                for (auto _item : _itemList)
                {
                    if (_item->text() == _name)
                    {
                        auto _pointElectricFieldData = m_mainWindow->getPointElectricFieldData();
                        if (!_pointElectricFieldData.isEmpty())
                        {
                            auto _findRes = _pointElectricFieldData.find(_item);
                            if (_findRes != _pointElectricFieldData.end())
                            {
                                _filePaths.append(_findRes.value());
                                break;
                            }
                        }
                        int _itemID = -1;
                        if (_item != nullptr)
                        {
                            if (!_item->data(Qt::UserRole + 10).isNull())
                                _itemID = _item->data(Qt::UserRole + 10).toInt();
                        }
                        auto _parser = getTextFileParserByProjectTreeItem(_itemID);
                        auto _fileName = _parser->GetFileName();
                        _filePaths.append(_fileName);
                        break;
                    }
                }
                if (emulationType == 1)//处理hirf外推数据
                {
                    auto _hirfExtrapolationCurveData = WindowTotalDataInstance->getHirfExtrapolationCurveData();
                    if (!_hirfExtrapolationCurveData.isEmpty())
                    {
                        auto _hirfValues = _hirfExtrapolationCurveData.values();
                        for (auto _hirfValue : _hirfValues)
                        {
                            if (_hirfValue == _name)
                            {
                                if (_hirfValue.contains(QRegularExpression(QStringLiteral("电场"))))
                                {
                                    auto _electricMergeData = WindowTotalDataInstance->getHirfExpElectricMergeDataFileData();
                                    auto values = _electricMergeData.values();
                                    if (!values.isEmpty())
                                    {
                                        QString _hirfFilePath = GlobalHelperInstance->getProjectTempIODir() + "/HirfExtrapolation" + "/" + values.first();
                                        if (!_filePaths.contains(_hirfFilePath))
                                            _filePaths.append(_hirfFilePath);
                                        break;
                                    }
                                }
                                else
                                {
                                    auto _hirfFileName = _hirfValue + ".txt";
                                    _hirfFileName.remove(QRegularExpression("V/m"));
                                    QString _hirfFilePath = GlobalHelperInstance->getProjectTempIODir() + "/HirfExtrapolation" + "/" + _hirfFileName;
                                    _filePaths.append(_hirfFilePath);
                                    break;
                                }
                            }
                        }
                    }
                }

            }
        }

        if (_filePaths.isEmpty())
        {
            auto _res = IdaDialogMsg::showDialog(nullptr, QStringLiteral("评估提交失败！"), EDialogMsg::Normal, QStringLiteral("失败"), {QStringLiteral("确定")});
            return;
        }

        QString dirName = g_outputDir;
        if (emulationType == 0)
        {
            dirName.append("/Lightning/");
        }
        else if (emulationType == 1)
        {
            dirName.append("/HIRF/");
        }
        else if (emulationType == 2)
        {
            dirName.append("/HPM/");
        }
        else if (emulationType == 3)
        {
            dirName.append("/HEMP/");
        }
        QDir _dir(dirName);
        if (!_dir.exists(dirName))
        {
            qDebug() << "Warning: Output path does not exist";
            auto isOk = _dir.mkpath(dirName);
            isOk ? qDebug() << "Output path creation succeeded!" : qDebug() << "Warning: Output path creation failed!";
        }

        //遍历_filePaths，将文件复制到_dir路径下
        for (auto _filePath : _filePaths)
        {
            QFile::copy(_filePath, dirName + "/" + QFileInfo(_filePath).fileName());
        }
        auto _res = IdaDialogMsg::showDialog(nullptr, QStringLiteral("评估提交成功！"), EDialogMsg::Normal, QStringLiteral("成功"), {QStringLiteral("确定")});

    }

    // 显示

    void MainWindowSignalHandler::slot_toolButtonSelfAdaptationClicked()
    {
        printErrorMessage();
    }
    void MainWindowSignalHandler::slot_toolButtonAmplifyClicked()
    {
        if (m_centerWidget == nullptr)
            return;
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();

        Graph2DWindowBase* graph2DWindow = qobject_cast<Graph2DWindowBase*>(currentGraph);
        if (graph2DWindow != nullptr)
        {
            graph2DWindow->slot_amplify();
            return;
        }

        Graph3DWindowBase* _window = qobject_cast<Graph3DWindowBase*>(currentGraph);
        if (_window == nullptr)
        {
            return;
        }
        _window->zoomCamera(1.2);
    }
    void MainWindowSignalHandler::slot_toolButtonMinificationClicked()
    {
        if (m_centerWidget == nullptr)
            return;
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();

        Graph2DWindowBase* graph2DWindow = qobject_cast<Graph2DWindowBase*>(currentGraph);
        if (graph2DWindow != nullptr)
        {
            graph2DWindow->slot_minification();
            return;
        }

        Graph3DWindowBase* _window = qobject_cast<Graph3DWindowBase*>(currentGraph);
        if (_window == nullptr)
        {
            return;
        }
        _window->zoomCamera(0.8);
    }
    void MainWindowSignalHandler::slot_toolButtonTranslationClicked(bool checked)
    {
        m_translationChosen = !m_translationChosen;
        m_rotationChosen = false;
        if (m_centerWidget == nullptr)
            return;
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        Graph3DWindowBase* _window = qobject_cast<Graph3DWindowBase*>(currentGraph);
        if (_window == nullptr)
        {
            return;
        }
        m_translationChosen ? _window->setInteractorStlyleToTranslation() : _window->setInteractorStlyleToDefault();
    }
    void MainWindowSignalHandler::slot_toolButtonRotationClicked(bool checked)
    {
        m_rotationChosen = !m_rotationChosen;
        m_translationChosen = false;
        if (m_centerWidget == nullptr)
            return;
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        Graph3DWindowBase* _window = qobject_cast<Graph3DWindowBase*>(currentGraph);
        if (_window == nullptr)
        {
            return;
        }
        _window->setInteractorStlyleToDefault(); // 默认就是旋转
    }

    void MainWindowSignalHandler::slot_toolButtonIsometricViewClicked()
    {
        printErrorMessage();
    }
    void MainWindowSignalHandler::slot_toolButtonTopViewClicked()
    {
        printErrorMessage();
    }
    void MainWindowSignalHandler::slot_toolButtonUpwardViewClicked()
    {
        printErrorMessage();
    }
    void MainWindowSignalHandler::slot_toolButtonFrontViewClicked()
    {
        printErrorMessage();
    }
    void MainWindowSignalHandler::slot_toolButtonRearViewClicked()
    {
        printErrorMessage();
    }
    void MainWindowSignalHandler::slot_toolButtonLeftViewClicked()
    {
        printErrorMessage();
    }
    void MainWindowSignalHandler::slot_toolButtonRightViewClicked()
    {
        printErrorMessage();
    }

    void pst::MainWindowSignalHandler::slot_updateClipperAndGeometry(bool isActiveClipper, bool isActiveGeometry, bool& hasAnyGeometrySuccess)
    {
        if (m_centerWidget == nullptr)
            return;
        m_isActiveClipper = isActiveClipper;
        m_isActiveGeometry = isActiveGeometry;
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        if (qobject_cast<Graph3DWindowBase*>(currentGraph) != nullptr)
        {
            // qobject_cast<Graph3DWindowBase*>(currentGraph)->setActiveClipper(checked);
            qobject_cast<Graph3DWindowBase*>(currentGraph)->updateClipperAndGeometry(isActiveClipper, isActiveGeometry, hasAnyGeometrySuccess);
        }
    }

    void pst::MainWindowSignalHandler::py_updateClipperAndGeometry(int windowUniversalID, bool isActiveClipper, bool isActiveGeometry, bool& hasAnyGeometrySuccess)
    {
        if (m_centerWidget == nullptr)
            return;
        m_isActiveClipper = isActiveClipper;
        m_isActiveGeometry = isActiveGeometry;
        Graph3DWindowBase* modelGraph = m_centerWidget->getGraph3DWindowBaseByUniversalID(windowUniversalID);
        if (modelGraph == nullptr)
            return;
        modelGraph->updateClipperAndGeometry(isActiveClipper, isActiveGeometry, hasAnyGeometrySuccess);
    }

    void pst::MainWindowSignalHandler::py_activeClipperSettingData(int windowUniversalID, bool toolButtonActiveClipperIsChecked, bool toolButtonModelDisplayIsChecked, bool hasAnyGeometrySuccess, QString direction, double clipperValue)
    {
        if (m_centerWidget == nullptr)
            return;

        Graph3DWindowBase* modelGraph = m_centerWidget->getGraph3DWindowBaseByUniversalID(windowUniversalID);
        if (modelGraph == nullptr)
            return;

        if (direction == "X")
        {
            modelGraph->setClipNormalDirection(1, 0, 0);
            modelGraph->setClipOrigin(clipperValue, 0, 0);
        }
        else if (direction == "Y")
        {
            modelGraph->setClipNormalDirection(0, 1, 0);
            modelGraph->setClipOrigin(0, clipperValue, 0);
        }
        else if (direction == "Z")
        {
            modelGraph->setClipNormalDirection(0, 0, 1);
            modelGraph->setClipOrigin(0, 0, clipperValue);
        }
        else if (direction == "-X")
        {
            modelGraph->setClipNormalDirection(-1, 0, 0);
            modelGraph->setClipOrigin(clipperValue, 0, 0);
        }
        else if (direction == "-Y")
        {
            modelGraph->setClipNormalDirection(0, -1, 0);
            modelGraph->setClipOrigin(0, clipperValue, 0);
        }
        else if (direction == "-Z")
        {
            modelGraph->setClipNormalDirection(0, 0, -1);
            modelGraph->setClipOrigin(0, 0, clipperValue);
        }

        modelGraph->updateClipperAndGeometry(toolButtonActiveClipperIsChecked, toolButtonModelDisplayIsChecked, hasAnyGeometrySuccess);
    }

    void MainWindowSignalHandler::slot_comboBoxNormalCurrentIndexChanged(int index)
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        if (m_centerWidget == nullptr)
            return;
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        if (qobject_cast<Graph3DWindowBase*>(currentGraph) != nullptr)
        {
            auto graph = qobject_cast<Graph3DWindowBase*>(currentGraph);
            QString direction = m_mainWindow->getClipperNormalDirection();
            double value = m_mainWindow->getClipperOriginDistance();
            if (direction == "X")
            {
                graph->setClipNormalDirection(1, 0, 0);
                graph->setClipOrigin(value, 0, 0);
            }
            else if (direction == "Y")
            {
                graph->setClipNormalDirection(0, 1, 0);
                graph->setClipOrigin(0, value, 0);
            }
            else if (direction == "Z")
            {
                graph->setClipNormalDirection(0, 0, 1);
                graph->setClipOrigin(0, 0, value);
            }
            else if (direction == "-X")
            {
                graph->setClipNormalDirection(-1, 0, 0);
                graph->setClipOrigin(value, 0, 0);
            }
            else if (direction == "-Y")
            {
                graph->setClipNormalDirection(0, -1, 0);
                graph->setClipOrigin(0, value, 0);
            }
            else if (direction == "-Z")
            {
                graph->setClipNormalDirection(0, 0, -1);
                graph->setClipOrigin(0, 0, value);
            }

            QWidget* currentGraph = m_centerWidget->getCurrentGraphWindow();
            int windowUniversalID = qobject_cast<Graph3DWindowBase*>(currentGraph)->getWindowUniversalID();
            QStringList _pyCodes{};
            _pyCodes += QString("activeclippersetting1 = PostProcessing.ActiveClipperSetting()");
            _pyCodes += QString("activeclippersetting1.setWindowUniversalId(%1)").arg((int)windowUniversalID);
            _pyCodes += QString("activeclippersetting1.setModelDisplaySettingData(%1,%2,%3)").arg(m_isActiveClipper).arg(m_isActiveGeometry).arg(false);
            _pyCodes += QString("activeclippersetting1.setActiveClipperSettingData('%1',%2)").arg(direction.toUtf8().data()).arg(value);
            _pyCodes += QString("activeclippersetting1.ActiveClipperSettingData()");
            emit IBaseSignalInstance->signal_execPYCode(_pyCodes, true, false);

            bool _noUse = false;
            graph->updateClipperAndGeometry(m_isActiveClipper, m_isActiveGeometry, _noUse);
        }
    }

    void MainWindowSignalHandler::slot_clipperOriginValueChanged(double value)
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        if (m_centerWidget == nullptr)
            return;
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        if (qobject_cast<Graph3DWindowBase*>(currentGraph) != nullptr)
        {
            auto graph = qobject_cast<Graph3DWindowBase*>(currentGraph);
            QString direction = m_mainWindow->getClipperNormalDirection();
            if (direction == "X")
            {
                graph->setClipNormalDirection(1, 0, 0);
                graph->setClipOrigin(value, 0, 0);
            }
            else if (direction == "Y")
            {
                graph->setClipNormalDirection(0, 1, 0);
                graph->setClipOrigin(0, value, 0);
            }
            else if (direction == "Z")
            {
                graph->setClipNormalDirection(0, 0, 1);
                graph->setClipOrigin(0, 0, value);
            }
            else if (direction == "-X")
            {
                graph->setClipNormalDirection(-1, 0, 0);
                graph->setClipOrigin(value, 0, 0);
            }
            else if (direction == "-Y")
            {
                graph->setClipNormalDirection(0, -1, 0);
                graph->setClipOrigin(0, value, 0);
            }
            else if (direction == "-Z")
            {
                graph->setClipNormalDirection(0, 0, -1);
                graph->setClipOrigin(0, 0, value);
            }

            QWidget* currentGraph = m_centerWidget->getCurrentGraphWindow();
            int windowUniversalID = qobject_cast<Graph3DWindowBase*>(currentGraph)->getWindowUniversalID();
            QStringList _pyCodes{};
            _pyCodes += QString("activeclippersetting1 = PostProcessing.ActiveClipperSetting()");
            _pyCodes += QString("activeclippersetting1.setWindowUniversalId(%1)").arg((int)windowUniversalID);
            _pyCodes += QString("activeclippersetting1.setModelDisplaySettingData(%1,%2,%3)").arg(m_isActiveClipper).arg(m_isActiveGeometry).arg(false);
            _pyCodes += QString("activeclippersetting1.setActiveClipperSettingData('%1',%2)").arg(direction.toUtf8().data()).arg(value);
            _pyCodes += QString("activeclippersetting1.ActiveClipperSettingData()");
            emit IBaseSignalInstance->signal_execPYCode(_pyCodes, true, false);

            bool _noUse = false;
            graph->updateClipperAndGeometry(m_isActiveClipper, m_isActiveGeometry, _noUse);
        }
    }

    void MainWindowSignalHandler::slot_toolButtonFastBackClicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        if (m_centerWidget == nullptr)
            return;

        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        if (qobject_cast<Graph3DWindowBase*>(currentGraph) != nullptr)
        {
            qobject_cast<Graph3DWindowBase*>(currentGraph)->decreaseAnimationSpeed();
            updateAnimationSpeedBottonState(qobject_cast<Graph3DWindowBase*>(currentGraph)->getSpeedFactor());
        }
        else if (qobject_cast<HeatMapWindow*>(currentGraph) != nullptr)
        {
            qobject_cast<HeatMapWindow*>(currentGraph)->decreaseAnimationSpeed();
            updateAnimationSpeedBottonState(qobject_cast<HeatMapWindow*>(currentGraph)->getSpeedFactor());
        }
    }

    void MainWindowSignalHandler::slot_toolButtonPlayClicked(bool checked)
    {
        if (m_centerWidget == nullptr)
            return;
        m_toolButtonPlayState = checked;
        if (m_toolButtonPlayState)
        {
            auto currentGraph = m_centerWidget->getCurrentGraphWindow();
            if (qobject_cast<Graph3DWindowBase*>(currentGraph) != nullptr)
            {
                updateAnimationSpeedBottonState(qobject_cast<Graph3DWindowBase*>(currentGraph)->getSpeedFactor());
            }
            else if (qobject_cast<HeatMapWindow*>(currentGraph) != nullptr)
            {
                updateAnimationSpeedBottonState(qobject_cast<HeatMapWindow*>(currentGraph)->getSpeedFactor());
            }
        }
        else
        {
            m_mainWindow->setToolButtonFastBackState(false);
            m_mainWindow->setToolButtonFastForwardState(false);
        }
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        if (qobject_cast<Graph3DWindowBase*>(currentGraph) != nullptr)
        {
            qobject_cast<Graph3DWindowBase*>(currentGraph)->setActiveAnimation(checked);
        }
        else if (qobject_cast<HeatMapWindow*>(currentGraph) != nullptr)
        {
            qobject_cast<HeatMapWindow*>(currentGraph)->setActiveAnimation(checked);
        }
    }

    void MainWindowSignalHandler::slot_toolButtonFastForwardClicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        if (m_centerWidget == nullptr)
            return;

        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        if (qobject_cast<Graph3DWindowBase*>(currentGraph) != nullptr)
        {
            qobject_cast<Graph3DWindowBase*>(currentGraph)->increaseAnimationSpeed();
            updateAnimationSpeedBottonState(qobject_cast<Graph3DWindowBase*>(currentGraph)->getSpeedFactor());
        }
        else if (qobject_cast<HeatMapWindow*>(currentGraph) != nullptr)
        {
            qobject_cast<HeatMapWindow*>(currentGraph)->increaseAnimationSpeed();
            updateAnimationSpeedBottonState(qobject_cast<HeatMapWindow*>(currentGraph)->getSpeedFactor());
        }
    }

    void MainWindowSignalHandler::slot_toolButtonDynamicTypeClicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        // printErrorMessage();
    }

    void MainWindowSignalHandler::slot_toolButtonDynamicTypeCameraClicked()
    {
        if (m_centerWidget == nullptr)
            return;
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        if (qobject_cast<Graph3DWindowBase*>(currentGraph) != nullptr)
        {
            qobject_cast<Graph3DWindowBase*>(currentGraph)->setAnimationType(1);
        }
        else if (qobject_cast<HeatMapWindow*>(currentGraph) != nullptr)
        {
            qobject_cast<HeatMapWindow*>(currentGraph)->setAnimationType(1);
        }
        m_mainWindow->setToolButtonDynamicTypeText(QStringLiteral("类型：相机"));
        m_isDynamicTypeCamera = true;
        m_mainWindow->updateAnimationButtonState();
    }

    void MainWindowSignalHandler::slot_toolButtonDynamicTypeDataClicked()
    {
        if (m_centerWidget == nullptr)
            return;
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        if (qobject_cast<Graph3DWindowBase*>(currentGraph) != nullptr)
        {
            qobject_cast<Graph3DWindowBase*>(currentGraph)->setAnimationType(0);
        }
        else if (qobject_cast<HeatMapWindow*>(currentGraph) != nullptr)
        {
            qobject_cast<HeatMapWindow*>(currentGraph)->setAnimationType(0);
        }
        m_mainWindow->setToolButtonDynamicTypeText(QStringLiteral("类型：数据"));
        m_isDynamicTypeCamera = false;
        m_mainWindow->updateAnimationButtonState();
    }

    void MainWindowSignalHandler::slot_toolButtonDynamicSettingClicked(bool isActionCameraEnable, bool isActionDataEnable)
    {
        if (m_centerWidget == nullptr)
            return;
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        //AnimationSettingData* data{m_centerWidget->getAnimationSettingData()};
        AnimationSettingData* data = nullptr;
        bool isActiveCamera{true};
        if (qobject_cast<Graph3DWindowBase*>(currentGraph) != nullptr)
        {
            data = qobject_cast<Graph3DWindowBase*>(currentGraph)->getAnimationSettingData();
            isActiveCamera = qobject_cast<Graph3DWindowBase*>(currentGraph)->getAnimationType(); // 0:数据变化 1 : 相机变化
        }
        else if (qobject_cast<HeatMapWindow*>(currentGraph) != nullptr)
        {
            data = qobject_cast<HeatMapWindow*>(currentGraph)->getAnimationSettingData();
            isActiveCamera = qobject_cast<HeatMapWindow*>(currentGraph)->getAnimationType(); // 0:数据变化 1 : 相机变化
        }
        else
        {
            return;
        }

        QPointer<AnimationSettingDialog> animationSettingDialog = new AnimationSettingDialog();
        animationSettingDialog->updateSetting(data);
        // if (isActionCameraEnable && isActionDataEnable)
        //{
        animationSettingDialog->setIsDynamicTypeCamera(isActiveCamera);
        //}
        // else
        // animationSettingDialog->setIsDynamicTypeCamera(!m_isDynamicTypeCamera);
        animationSettingDialog->showWindow();
    }

    void MainWindowSignalHandler::slot_toolButtonExportMotionGraphClicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        if (m_centerWidget == nullptr)
            return;

        QString fileName = QFileDialog::getSaveFileName(m_mainWindow, tr("导出动图"), "",
                                                        tr("gif 文件 (*.gif);;avi 文件 (*.avi)")); // 文件过滤器

        if (fileName.isEmpty())
        {
            return;
        }

        // 导出动图 包含热力图和三维云图、三维曲面图、表面电场图
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();

        if (qobject_cast<Graph3DWindowBase*>(currentGraph) != nullptr)
        {
            qobject_cast<Graph3DWindowBase*>(currentGraph)->exportAnimationData(fileName);
        }
        else if (qobject_cast<HeatMapWindow*>(currentGraph) != nullptr)
        {
            qobject_cast<HeatMapWindow*>(currentGraph)->exportAnimationData(fileName);
        }
        m_mainWindow->slot_setToolButtonExportMotionGraph2InterfaceState(false);
    }

    bool MainWindowSignalHandler::slot_computeHIRF(const QString& graphNames,
        double incidentWaveFieldValue, const QString& HIRFName, const QString& typeName, bool isCheckBoxChecked)
    {
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        auto lineChartWindow = qobject_cast<LineChartWindow*>(currentGraph);
        // 借助slot_checkGraphType判断的按钮是否可用来判断选中数据类型
        if (lineChartWindow == nullptr)
        {
            return false;
        }
        auto graphNameList = graphNames.split("\n");
        TextFileParser* textFileParser = nullptr;
        for (auto parser : m_mainWindow->m_HIRFExtrapolation)
        {
            if (QFileInfo(parser->GetFileName()).completeBaseName() == HIRFName)
            {
                textFileParser = parser;
                break;
            }
        }
        if (graphNameList.isEmpty() || textFileParser == nullptr)
        {
            return false;
        }
        return lineChartWindow->slot_computeHIRF(graphNameList, incidentWaveFieldValue, textFileParser, typeName, isCheckBoxChecked);
    }

    void MainWindowSignalHandler::updateAnimationSpeedBottonState(double speed)
    {
        speed < 2.0 ? m_mainWindow->setToolButtonFastForwardState(true) : m_mainWindow->setToolButtonFastForwardState(false);
        speed > 0.1 ? m_mainWindow->setToolButtonFastBackState(true) : m_mainWindow->setToolButtonFastBackState(false);
    }

    QStringList MainWindowSignalHandler::getInitParams(const LineChartWindow* lineChartWindow)
    {
        auto& curveMap = lineChartWindow->getCurve();
        QString params;
        for (auto& curvePair : curveMap)
        {
            auto item = curvePair.first;
            auto& info = curvePair.second;
            QCPGraph* graph = qobject_cast<QCPGraph*>(info->getCurveLineAddress());
            if (graph->selected())
            {
                params = item->data(Qt::UserRole + 3).toString();
                break;
            }
        }
        auto SEParamList = params.split(",", QString::SkipEmptyParts);
        //SEParamList.removeFirst();
        return SEParamList;
    }

    bool MainWindowSignalHandler::isEdit()
    {
        QObject* senderObj = sender();
        if (senderObj) {
            // 由信号触发的调用
            return false;
        }
        else {
            // 直接调用
            return true;
        }
    }

    void MainWindowSignalHandler::setToolButtonExportMotionGraphState(bool state)
    {
        m_mainWindow->setToolButtonExportMotionGraphState(state);
    }

    bool MainWindowSignalHandler::getIsDynamicTypeCamera()
    {
        return m_isDynamicTypeCamera;
    }

    void MainWindowSignalHandler::setIsDynamicTypeCamera(bool isCamera)
    {
        m_isDynamicTypeCamera = isCamera;
    }

    bool MainWindowSignalHandler::TextImportDataProcessing(int itemID, QString filePath, const QVector<std::tuple<QString, DialogDataImportConfiguration::DataProperty, QVector<double>>>& datas, QVector<QPair<QPointF, int>> resultFileData, FileDataTypes fileDataType)
    {
        if (resultFileData.count() != 5)
        {
            return false;
        }
        auto projectDataPointer = JsonParser::ProjectDataPointer::create();
        HearderFileInfo hearderFileInfo;
        auto resultFilePointer = ResultFilePointer::create();
        // x
        resultFilePointer->field_monitor_sample_info.sta_x = resultFileData.at(0).first.x();
        resultFilePointer->field_monitor_sample_info.end_x = resultFileData.at(0).first.y();
        resultFilePointer->field_monitor_sample_info.num_x = resultFileData.at(0).second;
        // y
        resultFilePointer->field_monitor_sample_info.sta_y = resultFileData.at(1).first.x();
        resultFilePointer->field_monitor_sample_info.end_y = resultFileData.at(1).first.y();
        resultFilePointer->field_monitor_sample_info.num_y = resultFileData.at(1).second;
        // z
        resultFilePointer->field_monitor_sample_info.sta_y = resultFileData.at(2).first.x();
        resultFilePointer->field_monitor_sample_info.end_y = resultFileData.at(2).first.y();
        resultFilePointer->field_monitor_sample_info.num_y = resultFileData.at(2).second;
        // theta
        resultFilePointer->field_monitor_sample_info.sta_theta = resultFileData.at(3).first.x();
        resultFilePointer->field_monitor_sample_info.end_theta = resultFileData.at(3).first.y();
        resultFilePointer->field_monitor_sample_info.num_theta = resultFileData.at(3).second;
        // phi
        resultFilePointer->field_monitor_sample_info.sta_phi = resultFileData.at(4).first.x();
        resultFilePointer->field_monitor_sample_info.end_phi = resultFileData.at(4).first.y();
        resultFilePointer->field_monitor_sample_info.num_phi = resultFileData.at(4).second;
        auto resultDataPointer = ResultDataPointer::create();

        resultDataPointer->fileType = fileDataType;
        resultDataPointer->resultFileInfo = resultFilePointer.toWeakRef();
        resultFilePointer->result_data.append(resultDataPointer);
        hearderFileInfo.result_info.append(resultFilePointer);
        projectDataPointer->projectFileData.append(hearderFileInfo);
        projectDataPointer->projectResultData.append(resultDataPointer);

        auto _isSuccess = m_mainWindow->TextImportDataProcessing(itemID,filePath,datas, projectDataPointer);
        return _isSuccess;
    }

    void MainWindowSignalHandler::printErrorMessage()
    {
        // auto _res = IdaDialogMsg::showDialog(nullptr, msg, EDialogMsg::Error, tr("导入失败列表"));
        auto _res = IdaDialogMsg::showDialog(nullptr, QStringLiteral("功能开发中！"), EDialogMsg::Warning, QStringLiteral("警告"), {QStringLiteral("确定")});
    }
} // namespace pst
